package com.jtpay.ysfproductionprocess.service;

import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.jtpay.ysfproductionprocess.R;
import com.jtpay.ysfproductionprocess.utils.ActivityHelper;
import com.jtpay.ysfproductionprocess.utils.LogUtil;
import com.jtpay.ysfproductionprocess.utils.PayFileUtil;
import com.jtpay.ysfproductionprocess.utils.SharedPreferenceUtil;

import java.util.List;

import static com.jtpay.ysfproductionprocess.utils.ActivityHelper.*;
import static com.jtpay.ysfproductionprocess.utils.PayContext.*;
import static com.jtpay.ysfproductionprocess.utils.PayFileUtil.HEADER_DATE_PATH;

/**
 * Description:
 * Date : 2018/06/01 09:06
 * Author : Joe
 */

public class UnionPayProductService extends AccessibilityService {

    private static final int DELAY_TIME_SHORT = 300;
    private static final int DELAY_TIME = 500;
    private boolean MainUIStep = false;//union pay ui start set money ui
    private int Count = 3;

    private Handler mHandler = new Handler();
    private SharedPreferenceUtil sharedPreferenceUtil = new SharedPreferenceUtil();


    /**
     * UnionPayProductService debug log show or not
     *
     * @param content String
     */
    private void log(String content) {
        LogUtil.logOnlySave(content);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        CharSequence charSequence = event.getPackageName();
        if (charSequence == null) {
            return;
        }

        String nowPackageName = charSequence.toString();
        if (nowPackageName.equals(UNION_PAY_PACKAGE_NAME)) {
//                || nowPackageName.equals("com.android.systemui")) {
            AccessibilityNodeInfo rootNode = this.getRootInActiveWindow();
            String className = event.getClassName().toString();
//            LogUtil.log("event className : " + className);
            switch (className) {
                case UNION_PAY_MAIN_ACTIVITY:
                    LogUtil.log("UNION_PAY_MAIN_ACTIVITY");
                    Count = 3;
                    doCallQrCodeUI(rootNode);
                    callUPAccountUI(rootNode);
                    break;
                case UNION_PAY_ROOT_DIALOG:
                    NEED_QR_PRODUCT_COUNT = NEED_QR_PRODUCT_COUNT_DEF;
                    doCancelRootDialog();
                    break;
                case UNION_PAY_MINE_ACTIVITY:
                    LogUtil.log("UNION_PAY_MINE_ACTIVITY");
                    boolean checkResult = checkUPAccount(rootNode);
                    if (checkResult) {
                        ActivityHelper.startProductMainActivity();
                        Intent intent = new Intent(ACTION_UNION_PAY_GET_HEADER);
                        LocalBroadcastManager.getInstance(UnionPayProductService.this).sendBroadcast(intent);
                    }
                    break;
                case UNION_PAY_P2P_TRANSFER_SET_AMOUNT_ACTIVITY:
                    /*if (SetMoney_step1 || SetMoney_step2 || SetMoney_step3) {
                        performGlobalAction(GLOBAL_ACTION_BACK);
                        break;
                    }
                    clickQrSetMoneyLabel(rootNode);*/
                    break;
                case "android.widget.FrameLayout":
                    doCancelMIUIAlertDialog();
                    break;
                case UNION_PAY_LOGIN_ACTIVITY:
                    CheckAccountStatus = 1;
                    PayFileUtil.delFile(HEADER_DATE_PATH);
                    LogUtil.log("******************UNION_PAY_LOGIN_ACTIVITY*******************" +
                            "\n need verify account");
                    break;
                default:
                    dealBlankPage(rootNode);
                    doCallQrCodeUI(rootNode);
                    break;
            }

        }
    }

    /**
     * doCancelMIUIAlertDialog
     */
    private void doCancelMIUIAlertDialog() {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = this.getRootInActiveWindow()
                    .findAccessibilityNodeInfosByViewId("miui:id/alertTitle");
        } catch (Exception e) {
            e.printStackTrace();
            log("findAccessibility NodeInfo ByViewId error : " + e.getMessage());
        }
        if (list != null && list.size() >= 1) {
            clickButton("android:id/button2");
        }
    }

    /**
     * click to cancel root alert dialog
     */
    private void doCancelRootDialog() {
        LogUtil.log("doCancelRootDialog");
        List<AccessibilityNodeInfo> listCancel = null;
        List<AccessibilityNodeInfo> list = null;
        List<AccessibilityNodeInfo> text = null;

        try {
            listCancel = this.getRootInActiveWindow()
                    .findAccessibilityNodeInfosByViewId(UNION_PAY_PACKAGE_NAME + ":id/btn_cancel");
            list = this.getRootInActiveWindow()
                    .findAccessibilityNodeInfosByViewId(UNION_PAY_PACKAGE_NAME + ":id/btn_ok");
            text = getRootInActiveWindow().findAccessibilityNodeInfosByText("知道了");
        } catch (Exception e) {
            e.printStackTrace();
            log("findAccessibility NodeInfo ByViewId error : " + e.getMessage());
        }
        // 点击取消自动更新弹窗
        if (listCancel != null && listCancel.size() >= 1) {
            clickButton(listCancel.get(0));
            LogUtil.log("doCancelUpdateDialog");
        }
        // 点击取消root弹窗
        if (list != null && list.size() >= 1 && text != null && text.size() >= 1) {
            clickButton(list.get(0));
            LogUtil.log("doCancelRootDialog");
            if (needSendBroadcast) {
                needSendBroadcast = false;
                startProductMainActivity();
                startUnionPayMainActivity();
                /*mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ActivityHelper.startProductMainActivity();
                        Intent intent = new Intent(ACTION_UNION_PAY_GET_HEADER);
                        LocalBroadcastManager.getInstance(UnionPayProductService.this).sendBroadcast(intent);
                    }
                }, 500);*/
            }
        }
    }

    /**
     * call UP UNION_PAY_MINE_ACTIVITY UI
     *
     * @param rootNode AccessibilityNodeInfo
     */
    private void callUPAccountUI(AccessibilityNodeInfo rootNode) {
        if (rootNode == null || CheckAccountStatus != 1) {
            return;
        }
        clickButton(UNION_PAY_PACKAGE_NAME + ":id/layout_title_right_image");
    }

    /**
     * check ysf account
     *
     * @param nodeInfo AccessibilityNodeInfo
     */
    private boolean checkUPAccount(AccessibilityNodeInfo nodeInfo) {

        if (nodeInfo == null || CheckAccountStatus != 1) {
            performGlobalAction(GLOBAL_ACTION_BACK);
            return false;
        }
        List<AccessibilityNodeInfo> list = null;
        try {
            list = getRootInActiveWindow()
                    .findAccessibilityNodeInfosByViewId(UNION_PAY_PACKAGE_NAME + ":id/tv_name");
        } catch (Exception e) {
            e.printStackTrace();
            log("findAccessibility NodeInfo ByViewId error : " + e.getMessage());
        }
        // 点击返回上一界面
        if (list != null && list.size() >= 1) {
            CheckAccountStatus = 2;
            String account = list.get(0).getText().toString();
            String programAccount = sharedPreferenceUtil.SP_READ(this, SP_SHOP_YSF_ACCOUNT_KEY);
            LogUtil.log("account " + account);
            ActivityHelper.startProductMainActivity();
            Intent intent = new Intent(ACTION_UNION_PAY_CHECK_ACCOUNT);
            intent.putExtra(BROADCAST_ACCOUNT_KEY, account);
            LocalBroadcastManager.getInstance(UnionPayProductService.this).sendBroadcast(intent);
            CheckAccountStatus = 0;
            return programAccount.equals(account);
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (Count > 0) {
                        boolean checkResult = checkUPAccount(getRootInActiveWindow());
                        LogUtil.log("checkResult " + checkResult);
                        if (checkResult) {
                            LogUtil.log("checkResult");
                            ActivityHelper.startProductMainActivity();
                            Intent intent = new Intent(ACTION_UNION_PAY_GET_HEADER);
                            LocalBroadcastManager.getInstance(UnionPayProductService.this).sendBroadcast(intent);
                        }
                        Count--;
                    }
                }
            }, 2000);
        }
        return false;
    }

    /**
     * initAndStartProduct
     */
    private void initAndStartProduct() {
        if (NEED_QR_PRODUCT_COUNT < 1) {
            return;
        }
        MainUIStep = clickButton(UNION_PAY_PACKAGE_NAME + ":id/tv_p2ptransfer_setAmt");
        if (!MainUIStep) {
            delayProductQr(DELAY_TIME_SHORT);
            return;
        }
        NEED_QR_PRODUCT_COUNT -= 1;
        if (NEED_QR_PRODUCT_COUNT == 0) {
            ActivityHelper.startProductMainActivity();
            Intent intent = new Intent(ACTION_UNION_PAY_GET_HEADER_RESULT);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        } else if (NEED_QR_PRODUCT_COUNT > 0) {
            delayProductQr(DELAY_TIME_SHORT);
        }
    }

    private void delayProductQr(final int delayTime) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initAndStartProduct();
            }
        }, delayTime);
    }

    /**
     * call BankCardList Window
     */
    private void callBankCardListWindow() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //call card list window
                boolean callListResult = clickButton(
                        UNION_PAY_PACKAGE_NAME + ":id/p2ptransfer_cardlist");
                if (callListResult) {
                    selectBankCard(0);
                } else {
                    callBankCardListWindow();
                }
            }
        }, DELAY_TIME);
    }

    /**
     * @param index index in listView
     * @return select result
     */
    private void selectBankCard(final int index) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //call card list window
                boolean selectBankCardResult = clickButton(
                        UNION_PAY_PACKAGE_NAME + ":id/item_root_view", index);
                if (selectBankCardResult) {
                    delayProductQr(DELAY_TIME);
                } else {
                    selectBankCard(index);
                }
            }
        }, DELAY_TIME);
    }

    /**
     * open qr show ui
     *
     * @param info AccessibilityNodeInfo
     */
    private void doCallQrCodeUI(AccessibilityNodeInfo info) {
//        log("doCallQrCodeUI NEED_QR_PRODUCT_COUNT " + NEED_QR_PRODUCT_COUNT);
        if (info == null || CheckAccountStatus != 0 || NEED_QR_PRODUCT_COUNT < 1) {
            return;
        }
        MainUIStep = false;
        clickButton(UNION_PAY_PACKAGE_NAME + ":id/tv_tab_name", 0);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                clickButton(UNION_PAY_PACKAGE_NAME + ":id/rbtn_table");
                delayProductQr(DELAY_TIME);
//                log("doCallQrCodeUI 2");
//                callBankCardListWindow();
            }
        }, DELAY_TIME);
    }

    /**
     * @param nodeInfo AccessibilityNodeInfo
     */
    private void dealBlankPage(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }
        if (nodeInfo.getChildCount() == 0 && nodeInfo.getText() != null) {
//            log("nodeInfo : " + nodeInfo.getText().toString());
            if (nodeInfo.getText().toString().endsWith(getString(R.string.reload))) {
                log(" dealBlankPage network error");
                clickButtonWithRoot(nodeInfo);
                delayProductQr(DELAY_TIME);
            }
        } else {
            for (int i = 0; i < nodeInfo.getChildCount(); i++) {
                if (nodeInfo.getChild(i) != null) {
                    dealBlankPage(nodeInfo.getChild(i));
                }
            }
        }
    }

    /**
     * @param viewId String resource-id
     * @param index  int index
     */
    private boolean clickButton(String viewId, int index) {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = this.getRootInActiveWindow().findAccessibilityNodeInfosByViewId(viewId);
        } catch (Exception e) {
            e.printStackTrace();
//            log("findAccessibility NodeInfo ByViewId " + viewId + " error : " + e.getMessage());
        }
        // click
        if (list != null && list.size() >= index + 1) {
            clickButton(list.get(index));
            return true;
        }
        return false;
    }

    /**
     * @param viewId String resource-id
     */
    private boolean clickButton(String viewId) {
        List<AccessibilityNodeInfo> list = null;
        try {
            list = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(viewId);
        } catch (Exception e) {
            e.printStackTrace();
//            log("findAccessibility NodeInfo ByViewId " + viewId + " error : " + e.getMessage());
        }
        // click
        if (list != null && list.size() >= 1) {
            clickButton(list.get(0));
            return true;
        }
        return false;
    }

    /**
     * @param info AccessibilityNodeInfo
     */
    private void clickButton(AccessibilityNodeInfo info) {
        AccessibilityNodeInfo parent = info;
        while (parent != null) {
            if (parent.isClickable()) {
                parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                break;
            }
            parent = parent.getParent();
        }
    }

    /**
     * @param nodeInfo use root command click
     */
    private void clickButtonWithRoot(final AccessibilityNodeInfo nodeInfo) {
//        log("clickButtonWithRoot");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Rect outBounds = new Rect();
                nodeInfo.getBoundsInScreen(outBounds);
                inputClick((outBounds.left + outBounds.right) / 2,
                        (outBounds.top + outBounds.bottom) / 2);
            }
        }, 300);
    }

    @Override
    public void onInterrupt() {
        Toast.makeText(this, "onInterrupt", Toast.LENGTH_SHORT).show();
    }
}
